#include "download.h"

void Download::DownloadFile()
{
    m_reply = m_accessmanager->get(QNetworkRequest(*m_url));
    connect(m_reply, SIGNAL(finished()), this, SLOT(downloadFinished()));
    connect(m_reply, SIGNAL(downloadProgress(qint64,qint64)),
            this, SLOT(progress(qint64,qint64)));
    connect(m_button, SIGNAL(clicked()), this, SLOT(stop()));
    m_button->setText(tr("Stop"));
    m_text->setText(tr("Downloading: %1").arg(*m_filename));
}

void Download::OpenFile()
{
}

void Download::progress(qint64 a, qint64 b)
{
    m_progressbar->setMaximum(b);
    m_progressbar->setValue(a);
}

void Download::stop()
{
    m_text->setText(tr("Stoped"));
    m_button->setDisabled(true);
    m_reply->abort();
}

void Download::downloadFinished()
{
    if(m_reply->error())
    {
        myLog::error(__FILE__,__FUNCTION__,m_reply->errorString().toUtf8());
        m_text->setText(m_reply->errorString());
        m_button->setDisabled(true);
    }
    else
    {
        m_file = new QByteArray(m_reply->readAll());
        QFile save(*m_filename);
        if(save.open(QIODevice::WriteOnly))
        {
            save.write(*m_file);
            save.flush();
            save.close();
            QMessageBox::information(this,tr("Finish"),
                               tr("Downloaded: %1").arg(*m_filename),
                                     QMessageBox::Ok);
            m_button->setText(tr("Open"));
            connect(m_button, SIGNAL(clicked()), this, SLOT(OpenFile()));
            m_button->setDisabled(true);
        }
    }
}

int Download::savePath(const QUrl &url)
{
    QString defaultFileName = QFileInfo(url.toString()).fileName();
    m_filename =
            new QString(QFileDialog::getSaveFileName(this,
                                                     tr("Save File"),
                                                     defaultFileName));
    if(m_filename->isEmpty())
        return 0;
    m_url = new QUrl(url);
    return 1;
}

void Download::setAccessManager(myNetworkAccessManager *manager)
{
    m_accessmanager = manager;
}

Download::Download(QWidget *parent) :
    QWidget(parent),
    settings(new MySettings),
    m_progressbar(new QProgressBar(this)),
    m_text(new QLabel(this)),
    m_reply(NULL),
    m_button(new QToolButton(this)),
    m_filename(NULL),
    m_file(NULL),
    m_layout(new QHBoxLayout(this)),
    m_url(NULL)
{
    m_layout->addWidget(m_text);
    m_layout->addWidget(m_progressbar);
    m_layout->addWidget(m_button);
}

Download::~Download()
{
    m_reply->abort();
    delete settings;
    delete m_file;
}
